package com.yupi.springbootinit.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.common.BaseResponseXzh;
import com.yupi.springbootinit.common.ErrorCodeXzh;
import com.yupi.springbootinit.config.WxOpenConfig;
import com.yupi.springbootinit.exception.BusinessExceptionXzh;
import com.yupi.springbootinit.model.dto.user.UserLoginRequest;
import com.yupi.springbootinit.model.dto.user.UserRegisterRequest;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.service.UserService;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserCollentXzh {
    @Resource
    private UserService userService;
    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "xzh";

    @Resource
    private WxOpenConfig wxOpenConfig;

    @PostMapping("/register")
    public BaseResponseXzh<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        // 都不能为空
        if (StringUtils.isAnyBlank(userRegisterRequest.getUserPassword(), userRegisterRequest
                .getUserAccount(), userRegisterRequest.getCheckPassword())) {
            return BaseResponseXzh.userError(ErrorCodeXzh.PARAMS_ERROR);
        }


        // 密码大于8位
        // 账户大于6位 并且 没有特殊符号
        // 密码一二次相同  假设都做了验证
        // 账户不能重复  防止中间有人注册 要用索
        synchronized (userRegisterRequest.getUserAccount().intern()) {
            long count = userService.count(new QueryWrapper<User>().eq("userAccount", userRegisterRequest.getUserAccount()));
            if (count > 0) {
                return BaseResponseXzh.userError("账户不能重复");
            }
            // 密码加密
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((SALT + userRegisterRequest.getUserPassword()).getBytes());
            // 保存到数据库
            User user = BeanUtil.copyProperties(userRegisterRequest, User.class);
            user.setUserPassword(md5DigestAsHex);
            boolean save = userService.save(user);
            if (!save) {
                return BaseResponseXzh.error("数据库插入失败");
            }
        }
        return BaseResponseXzh.success();
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ApiModelProperty(value = "用户登录")
    public BaseResponseXzh<LoginUserVO> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 校验
        // 非空判断
        if (Objects.isNull(userLoginRequest)) {
            return BaseResponseXzh.userError(ErrorCodeXzh.PARAMS_ERROR);
        }
        // 校验账户 密码 是否正确
        // 对密码加密 和数据库进行比较
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((SALT + userLoginRequest.getUserPassword()).getBytes());
        User user = userService.getOne(new QueryWrapper<User>().eq("userAccount", userLoginRequest.getUserAccount())
                .eq("userPassWord", md5DigestAsHex));
        if (Objects.isNull(user)) {
            return BaseResponseXzh.userError("用户名或账户不正确");
        }
        // 记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        // 封装返回结果
        LoginUserVO vo = BeanUtil.copyProperties(user, LoginUserVO.class);
        return BaseResponseXzh.success(vo);
    }

    /**
     * 用户注销
     */
    @PostMapping("logout")
    public BaseResponseXzh<String> logout(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return BaseResponseXzh.userError(ErrorCodeXzh.PARAMS_ERROR);
        }
        // 移除session
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return BaseResponseXzh.success();
    }
    /**
     * 获得当前登录用户信息
     */
    @GetMapping("/getlogin")
    public BaseResponseXzh<User> getlogin(HttpServletRequest request){
        // 先判断是否登录
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser=(User) attribute;
        if (Objects.isNull(currentUser)||Objects.isNull(currentUser.getId())){
            throw new BusinessExceptionXzh(ErrorCodeXzh.NOT_LOGIN_ERROR);
        }
        // 从数据库读取数据
        User user = userService.getById(currentUser.getId());
        if (Objects.isNull(user)){
            throw new BusinessExceptionXzh(ErrorCodeXzh.NOT_LOGIN_ERROR);
        }
        return BaseResponseXzh.success(user);
    }
}
